// ==UserScript==
// @name         吾爱小插件(管理专用)
// @namespace    http://www.lingmx.com/
// @version      0.2.4
// @description  自己用的小功能!
// @author       52pojie-含笑阁
// @match        https://www.52pojie.cn/*
// @grant        none
// @icon         https://www.lingmx.com/52pj/images/noavatar_middle.png
// @require      http://libs.baidu.com/jquery/1.8.3/jquery.min.js
// @homepage     https://www.lingmx.com/52pj/52MiniPlug-in.html
// @updateURL    https://gitee.com/lingmx/hxg-52pj-darkmode/raw/master/52pojie.user.js
// @downloadURL  https://gitee.com/lingmx/hxg-52pj-darkmode/raw/master/52pojie.user.js
// @license      GPL-3.0-only
// @run-at       document-start
// ==/UserScript==

/**
 * V0.2.4
 * 新增黑夜模式,版规速查按钮现在可以拖动调整位置了
 * 2021年8月4日
 */
/**
 * V0.2.3
 * 添加一键热心+1,一键cb+1,一键已处理，一键已答复功能
 * 2021年4月3日
 */

(function() {
    'use strict';
    // Code Start !

    // -------------------------------
    // ------------默认值配置----------
    // -------------------------------
    // 给jQuery设置个别名，因为论坛占用了_$
    var _$ = jQuery.noConflict();

    /**
     * CONFIG 默认配置(先清除掉localStorage再修改)
     * name: 设置面板显示内容
     * state: 默认开关
     */
    var CONFIG = {
        HIDETOP: { name: "隐藏置顶", state: false },
        HIDERULES: { name: "隐藏版规", state: false },
        OPTIMIZEIMG: { name: "图片优化", state: false },
        ADMINREPLY: { name: "快捷回复", state: true },
        QUERYRULES: { name: "版规速查", state: false },
        DARKMODE: { name: "夜深人静", state: false }
    }

    /**
     * 快捷回复短语
     * value: option value值
     * words: option 显示内容
     * detail: 输入框中输入的文字
     */
    var _RuplayList_ = [
        { value: 0, words: "快捷短语", detail: "" },
        { value: 1, words: "消除违规", detail: "积极改正的第一次可以 130热心兑换-1违规(在站务区发帖申请，管理会根据热心获得情况给予批复)，第二次需要260热心兑换1点违规，第三次需要520热心兑换1点违规，每人最多只能兑换3点违规，获得违规一个月后才可以申请热心消除，并且这一个月内必须不再违规，否则申请不通过。 @Hmily" },
        { value: 2, words: "撤销悬赏", detail: "您好，悬赏帖发布14天后如问题未得到解决或自行解决可按撤销规则回帖申请撤销。 \n悬赏区申请撤销悬赏地址：https://www.52pojie.cn/thread-1343495-1-1.html" },
        { value: 3, words: "版权维权", detail: "您好，请提供著作权或者有效证明发送到官方邮箱service艾特52pojie.cn，会有人跟进处理。" },
        { value: 4, words: "催审核的", detail: "您好，审核帖子最长会在3-7个工作日内进行处理（开放注册后审核帖子多就会慢），请耐心等待。" },
    ];

    /**
     * 设置LOG颜色
     * w: 要打印的文字
     * color: 文字的颜色
     */
    var LOGGER = {
        Danger: function(w) {
            console.log('%c' + new Date().toLocaleTimeString() + ": " + w, 'color:#F56C6C')
        },
        Success: function(w) {
            console.log('%c' + new Date().toLocaleTimeString() + ": " + w, 'color:#67C23A')
        },
        Primary: function(w) {
            console.log('%c' + new Date().toLocaleTimeString() + ": " + w, 'color:#409EFF')
        },
        Warning: function(w) {
            console.log('%c' + new Date().toLocaleTimeString() + ": " + w, 'color:#E6A23C')
        },
        Info: function(w) {
            console.log('%c' + new Date().toLocaleTimeString() + ": " + w, 'color:#909399')
        }
    }


    // -------------------------------
    // ----------插件初始化------------
    // -------------------------------
    function HXG_Init() {

        LOGGER.Info('插件开始加载');
        // 清理旧版本缓存
        let VersionNum = localStorage.getItem('VersionNum');
        if (!VersionNum || VersionNum != "0.2.4") {
            localStorage.clear()
        }
        localStorage.setItem('VersionNum', '0.2.4')

        // 加载插件样式
        let _style_ = document.createElement('link');
        _style_.href = 'https://www.lingmx.com/52pj/_style.css';
        _style_.rel = 'stylesheet';
        _style_.type = 'text/css';
        _$('head').append(_style_)
        LOGGER.Info('样式加载成功')
            // 添加插件控制按钮及面板
        let _SETTING_BTN = `<a href='javascript:;' id='_SETTING_BTN'>吾爱小插件</a>`;
        _$('#toptb .y').append(_SETTING_BTN);
        _$('#_SETTING_BTN').click(function() {
            _$('._set_div').toggle();
        });

        // 加载配置
        let __CONFIG = localStorage.getItem('__HXG_CONFIG__');
        if (__CONFIG && __CONFIG.length > 10) {
            // 加载本地配置
            CONFIG = JSON.parse(__CONFIG);
            LOGGER.Info('加载本地配置')
        } else {
            LOGGER.Info('加载默认配置')
            localStorage.setItem('__HXG_CONFIG__', JSON.stringify(CONFIG))
        }
        // 加载配置面板
        let _SETTING_DIV = document.createElement('div');
        _SETTING_DIV.className = "_set_div";
        let _SETITEM = "";
        for (let item in CONFIG) {
            _SETITEM += `<div class="_set_item">
                            <span>${CONFIG[item].name}</span>
                            <label class="el-switch el-switch-sm el-checkbox-green">
                                <input type="checkbox" class="_set_input" data-item="${item}" ${CONFIG[item].state ? 'checked' : ''} >
                                <span class="el-switch-style"></span>
                            </label>
                        </div>`
        }
        _SETTING_DIV.innerHTML = _SETITEM;
        _$('body').append(_SETTING_DIV);
        _$('._set_div').hover(function() {
                _$('._set_div').show()
            }, function() {
                _$('._set_div').hide()
            })
            // 添加配置项点击事件
        _$("._set_input").change(function() {
            let state = _$(this).attr('checked');
            let _item = _$(this).attr('data-item');
            CONFIG[_item].state = state;
            localStorage.setItem('__HXG_CONFIG__', JSON.stringify(CONFIG))
            if (state) {
                LOGGER.Success(`打开: ${CONFIG[_item].name}`)
            } else {
                LOGGER.Warning(`关闭: ${CONFIG[_item].name}`)
            }
            _UpdateStatus();
        });
        // 载入图片优化 (还需优化 需等图片加载完成后才可生效)
        try {
            let IMGOBJ = _$('img[id^="aimg"]');
            IMGOBJ.each(function() {
                let _img = new Image();
                let _that = this;
                _img.src = _$(this).attr('src');
                _img.onload = function() {
                    if (_img.height > _img.width) {
                        _$(_that).css('height', 'auto');
                        _$(_that).css('max-width', '400px');
                    }
                }
            })
            LOGGER.Success('图片优化加载成功')
        } catch (error) {
            LOGGER.Danger('图片优化加载失败，该页面无图片')
        }
        // 载入快捷回复
        try {
            let SelectObj = `<select name="ShortcutPhrase" id="ShortcutPhrase" class="ShortcutPhrase">`;
            for (let i = 0; i < _RuplayList_.length; i++) {
                SelectObj += `<option value="${_RuplayList_[i].value}">${_RuplayList_[i].words}</option>`;
            }
            SelectObj += "</select>";
            _$('#fastpostat').after(SelectObj);
            var obj = _$("#ShortcutPhrase")[0];
            obj.onchange = function() {
                var index = obj.selectedIndex;
                _$('#fastpostmessage').val(_RuplayList_[index].detail);
                // 是否自动点击回复按钮，默认关闭，不建议使用
                // if (CONFIG.AUTOREPLY.state) {
                //     _$('#fastpostsubmit')[0].click();
                // }
            }
            LOGGER.Success('快捷回复加载成功')
        } catch (error) {
            LOGGER.Danger('快捷回复加载失败，当前页面无回复窗口')
        }
        // 加载版规速查
        let _QueryRule_ = document.createElement('div');
        _QueryRule_.className = '_rule_div';

        let _QueryRuleBtn_ = document.createElement('div');
        _QueryRuleBtn_.className = 'rule_btn';
        _QueryRuleBtn_.innerHTML = "版";
        _$('body').append(_QueryRule_);

        // 添加搜索框
        let _SearchInput_ = document.createElement('input');
        _SearchInput_.type = "text";
        _SearchInput_.id = "QRSearch";
        _SearchInput_.className = "_qr_search"

        // 添加搜索结果框
        let _SearchResults_ = document.createElement('div');
        _SearchResults_.className = "_qr_search_result"

        _$('._rule_div').append(_QueryRuleBtn_);
        _$('._rule_div').append(_SearchInput_);
        _$('._rule_div').append(_SearchResults_);
        var firstTime = null;
        var lastTime = null;
        let TOPNUMBER = localStorage.getItem('RULEBTN_TOP');
        if (TOPNUMBER) {
            _$('.rule_btn').attr('style', "top:" + TOPNUMBER + "px");
        }
        _$('.rule_btn').on({
            mousedown: function(event) {
                firstTime = new Date().getTime();
                var e = e || window.event;
                //获取按下的位置
                var h = e.clientY;
                //获得是鼠标按下时相对于元素的位置
                var ey = (h - _$('.rule_btn').offset().top) / 2;
                if (ey < 0 || ey > 30) {
                    ey = 10
                }
                _$('._rule_div')[0].onmousemove = function(h) {
                    var h = h || window.event;
                    var h1 = h.clientY;
                    _$('.rule_btn').attr('style', "top:" + (h1 - ey) + "px");
                    localStorage.setItem('RULEBTN_TOP', h1 - ey)
                }
            },
            mouseup: function() {
                lastTime = new Date().getTime();
                if ((lastTime - firstTime) < 200) {
                    _$('._rule_div').toggleClass('active')
                }
                _$('._rule_div')[0].onmousemove = null;
            }
        })

        // 添加搜索事件
        _$('._qr_search').on('input', function(e) {
            let url = encodeURI('https://52pj.lingmx.com/GetRulesList?keywords=' + _$(this).val())
            _$.ajax({
                type: 'GET',
                url: url,
                dataType: "json",
                success: result => {
                    if (result.code == 0) {
                        let _CallBack_ = "";
                        let CBList = result.data;
                        for (let i = 0; i < CBList.length; i++) {
                            _CallBack_ += `
                                <div class="_result_item_box">
                                    <div class="_rules_title">${CBList[i][3]}</div>
                                    <div class="_rules_detail">详情：<br>${CBList[i][4]}</div>
                                    <div class="_proposal_div">
                                        <div class="_proposal_punish">建议处罚：- </div>
                                        <div class="_proposal_punish_reasons">建议理由：- </div>
                                    </div>
                                    <div class="_rules_bot">
                                        <a href="${CBList[i][8]}" target="_blank">${CBList[i][7]}</a>
                                    </div>
                                </div>
                            `
                        }
                        _$('._qr_search_result').html(_CallBack_)
                    } else {
                        _$('._qr_search_result').html("版规速查-V0.1-52pj含笑阁")
                    }
                },
                error: err => {
                    _$('._qr_search_result').html("版规速查-V0.1-52pj含笑阁")
                }
            })
        });
        // 添加一键评分按钮
        try {
            let _TabList_ = _$('table[id^="pid"]');
            for (let i = 0; i < _TabList_.length; i++) {
                let _Parent_ = _TabList_[i].querySelector('.pob.cl> p');
                let _ANode_ = _TabList_[i].querySelector('.pob.cl> p a');
                let Nhtml = `<a href="javascript:;" data-i="0" data-pid="${_TabList_[i].getAttribute('id').slice(3)}">热心+1</a>`
                let Nhtml2 = `<a href="javascript:;" data-i="1" data-pid="${_TabList_[i].getAttribute('id').slice(3)}">CB+1</a>`
                let tempNode = document.createElement('a');
                let tempNode2 = document.createElement('a');
                tempNode.innerHTML = Nhtml;
                tempNode2.innerHTML = Nhtml2;
                Nhtml = tempNode.firstChild;
                Nhtml2 = tempNode2.firstChild;
                Nhtml.onclick = SnedScore;
                Nhtml2.onclick = SnedScore;


                function SnedScore() {
                    let index = _$(this).data("i");
                    let pid = _$(this).data("pid");
                    // console.log(tid)
                    eval(`showWindow('rate', 'forum.php?mod=misc&action=rate&tid=${tid}&pid=${pid}', 'get', -1);`)
                    setTimeout(() => {
                        if (index == 0) {
                            _$('#score6')[0].value = "1"
                            _$('#reason')[0].value = "已经处理，感谢您对吾爱破解论坛的支持！"
                        } else {
                            _$('#score2')[0].value = "1"
                            _$('#reason')[0].value = "已经处理，感谢您对吾爱破解论坛的支持！"
                        }
                    }, 500);
                }
                _Parent_.prepend(Nhtml)
                _Parent_.prepend(Nhtml2)
            }
        } catch (error) {
            LOGGER.Warning(error)
        }

        // 已处理
        try {
            let _NavList_ = _$('#modmenu');
            let html = `<a href="javascript:;">已处理</a>`;
            let tempNode = document.createElement('a');
            tempNode.innerHTML = html;
            html = tempNode.firstChild;
            html.onclick = function() {
                modthreads(2, 'type')
                setTimeout(() => {
                    if (fid == 72) {
                        _$('#typeid')[0].value = 285;
                    } else if (fid == 15) {
                        _$('#typeid')[0].value = 21;
                    }
                    _$('#reason')[0].value = "已经处理，感谢您对吾爱破解论坛的支持！"
                }, 500);
            }

            _NavList_.append(html)
            _NavList_.append(`<span class="pipe">|</span>`)
        } catch (error) {
            LOGGER.Warning(error)
        }

        // 已答复
        try {
            let _NavList_ = _$('#modmenu');
            let html = `<a href="javascript:;">已答复</a>`;
            let tempNode = document.createElement('a');
            tempNode.innerHTML = html;
            html = tempNode.firstChild;
            html.onclick = function() {
                modthreads(2, 'type')
                setTimeout(() => {
                    if (fid == 72) {
                        _$('#typeid')[0].value = 288;
                    } else if (fid == 15) {
                        _$('#typeid')[0].value = 206;
                    }
                    _$('#reason')[0].value = "已经处理，感谢您对吾爱破解论坛的支持！"
                }, 500);
            }

            _NavList_.append(html)

        } catch (error) {
            LOGGER.Warning(error)
        }

        _UpdateStatus();

    }


    // 刷新插件
    function _UpdateStatus() {
        // 置顶内容
        if (CONFIG.HIDETOP.state) {
            _$('tbody[id^="stickthread"]').hide();
        } else {
            _$('tbody[id^="stickthread"]').show();
        }
        // 版块顶部版规
        if (CONFIG.HIDERULES.state) {
            _$('.bm_c.cl.pbn').hide();
        } else {
            _$('.bm_c.cl.pbn').show();
        }
        // 图片优化
        if (CONFIG.OPTIMIZEIMG.state) {
            try {
                let IMGOBJ = _$('img[id^="aimg"]');
                IMGOBJ.each(function() {
                    let _img = new Image();
                    let _that = this;
                    _img.src = _$(this).attr('src');
                    _img.onload = function() {
                        if (_img.height > _img.width) {
                            _$(_that).css('height', 'auto');
                            _$(_that).css('max-width', '400px');
                        }
                    }
                })
                LOGGER.Success('图片优化加载成功')
            } catch (error) {
                LOGGER.Danger('图片优化加载失败，该页面无图片')
            }
        } else {
            let IMGOBJ = _$('img[id^="aimg"]');
            IMGOBJ.each(function() {
                _$(this).removeAttr('style');
            })
        }
        // 快捷回复
        if (CONFIG.ADMINREPLY.state) {
            _$("#ShortcutPhrase").show();
        } else {
            _$("#ShortcutPhrase").hide();
        }
        // 版规速查
        if (CONFIG.QUERYRULES.state) {
            _$("._rule_div").show();
        } else {
            _$("._rule_div").hide();
        }
        // 黑夜模式
        if (CONFIG.DARKMODE.state) {
            let _dark_style_ = document.createElement('link');
            _dark_style_.href = 'https://www.lingmx.com/52pj/_dark.css';
            _dark_style_.rel = 'stylesheet';
            _dark_style_.type = 'text/css';
            _dark_style_.id = "hxg_dark_css"
            _$('head').append(_dark_style_)

        } else {
            let darkcss = document.getElementById("hxg_dark_css")
            if (darkcss) {
                document.head.removeChild(darkcss)
            }
        }
    }

    // 监听 站内查重
    document.addEventListener("dblclick", doubleClick, true);
    document.addEventListener("mouseup", mouseUp, true);

    function doubleClick(e) {
        var text = "";
        if (window.getSelection) {
            text = window.getSelection().toString();
        } else if (document.selection && document.selection.type != "Control") {
            text = document.selection.createRange().text;
        }
        if ("" != text) {
            _$('#WordsNav').attr('style', `position:fixed;top:${e.y - 40}px;left:${e.x}px;width:30px;height:30px;background:url('https://avatar.52pojie.cn/images/noavatar_middle.gif') no-repeat center center;background-size:cover`)
            _$('#WordsNav').attr('href', 'https://www.baidu.com/s?wd=' + text + "%20site:www.52pojie.cn")
        } else {
            _$('#WordsNav').removeAttr('style')
        }

    }

    function mouseUp(e) {
        var text = "";
        if (window.getSelection) {
            text = window.getSelection().toString();
        } else if (document.selection && document.selection.type != "Control") {
            text = document.selection.createRange().text;
        }
        if ("" != text) {
            _$('#WordsNav').attr('style', `position:fixed;top:${e.y - 40}px;left:${e.x}px;width:30px;height:30px;background:url('https://avatar.52pojie.cn/images/noavatar_middle.gif') no-repeat center center;background-size:cover`)
            _$('#WordsNav').attr('href', 'https://www.baidu.com/s?wd=' + text + "%20site:www.52pojie.cn")
        } else {
            _$('#WordsNav').removeAttr('style')
        }
    }

    let WordsNav = document.createElement('a');
    WordsNav.id = "WordsNav";
    WordsNav.title = "一键查重";
    WordsNav.target = "_blank";
    _$('body').append(WordsNav)



    window.onload = function() {
        HXG_Init();
    }
})();